# This file contains functions to create views to add to databases

import couchdb
import couchdb.design 

################################ Emails #####################################################################

def emailView(database):
    # add the view which returns all the email documents
    func = '''
            function(doc) {
                if (doc.doc_type == "Email")
                    emit(doc);
            }
           '''
    view=couchdb.design.ViewDefinition('emailview', 'emailview', func)
    view.sync(database)
    small = '''
            function(doc) {
                if (doc.doc_type == "Email")
                    emit(doc.date, {id: doc._id, date: doc.date, sender: doc.sender, subject: doc.subject});
            }
           '''
    view=couchdb.design.ViewDefinition('smallemailview', 'smallemailview', small)
    view.sync(database)
    
def emailsMonthCounter(database):
    # view that counts the commits in a given month
    map = '''
            function(doc) {
                if (doc.doc_type == "Email")
                    emit(doc.date.substring(0,7), 1);
            }
           '''
    reduce = '''
                function(keys, values, rereduce) {
                    return sum(values);
                }
             '''
    view=couchdb.design.ViewDefinition('emailMonthCount', 'emailMonthCount', map_fun=map, reduce_fun=reduce)
    view.sync(database)

def emailsYearCounter(database):
    # view that counts the commits in a given year
    map = '''
            function(doc) {
                if (doc.doc_type == "Email")
                    emit(doc.date.substring(0,4), 1);
            }
           '''
    reduce = '''
                function(keys, values, rereduce) {
                    return sum(values);
                }
             '''
    view=couchdb.design.ViewDefinition('emailYearCount', 'emailYearCount', map_fun=map, reduce_fun=reduce)
    view.sync(database)
 
def emailsDayCounter(database):
    # view that counts the emails in a given day
    map = '''
            function(doc) {
                if (doc.doc_type == "Email")
                    emit(doc.date.substring(0,10), 1);
            }
           '''
    reduce = '''
                function(keys, values, rereduce) {
                    return sum(values);
                }
             '''
    view=couchdb.design.ViewDefinition('emailDayCount', 'emailDayCount', map_fun=map, reduce_fun=reduce)
    view.sync(database)     
###############################################################################################################

############################# Commits #########################################################################
    
def commitView(database):
    # add the view which returns all the commit documents
    func = '''
            function(doc){
                if (doc.doc_type == "Commit")
                    emit(doc);
            }
           '''
    view=couchdb.design.ViewDefinition('commitview', 'commitview', func)
    view.sync(database)
    small = '''
            function(doc) {
                if (doc.doc_type == "Commit")
                    emit(doc.date, {id: doc._id, date: doc.date, author: doc.author, log: doc.logMessage});
            }
           '''
    view=couchdb.design.ViewDefinition('smallcommitview', 'smallcommitview', small)
    view.sync(database)
    
def commitsMonthCounter(database):
    # view that counts the commits in a given month
    map = '''
            function(doc) {
                if (doc.doc_type == "Commit")
                    emit(doc.date.substring(0,7), 1);
            }
           '''
    reduce = '''
                function(keys, values, rereduce) {
                    return sum(values);
                }
             '''
    view=couchdb.design.ViewDefinition('commitMonthCount', 'commitMonthCount', map_fun=map, reduce_fun=reduce)
    view.sync(database)

def commitsYearCounter(database):
    # view that counts the commits in a given year
    map = '''
            function(doc) {
                if (doc.doc_type == "Commit")
                    emit(doc.date.substring(0,4), 1);
            }
           '''
    reduce = '''
                function(keys, values, rereduce) {
                    return sum(values);
                }
             '''
    view=couchdb.design.ViewDefinition('commitYearCount', 'commitYearCount', map_fun=map, reduce_fun=reduce)
    view.sync(database)
    
def commitsDayCounter(database):
    # view that counts the commits in a given day
    map = '''
            function(doc) {
                if (doc.doc_type == "Commit")
                    emit(doc.date.substring(0,10), 1);
            }
           '''
    reduce = '''
                function(keys, values, rereduce) {
                    return sum(values);
                }
             '''
    view=couchdb.design.ViewDefinition('commitDayCount', 'commitDayCount', map_fun=map, reduce_fun=reduce)
    view.sync(database)    
###################################################################################################################

################################### Issues ########################################################################
    
def issueView(database):
    # add the view which returns all the issues documents
    func = '''
            function(doc){
                if (doc.doc_type == "Issue")
                    emit(doc.dateReported, doc);
            }
           '''
    view=couchdb.design.ViewDefinition('issueview', 'issueview', func)
    view.sync(database)

def issuesMonthCounter(database):
    # view that counts the issues in a given month
    map = '''
           function(doc) {
                if(doc.doc_type=="Issue"){
                    dataStart=doc.dateReported.substring(0,7)
                    dataEnd=doc.dateUpdated.substring(0,7)
                    startYear = dataStart.split("-")[0].toString()
                    startYear = parseInt(startYear, 10)
                    startMonth = dataStart.split("-")[1].toString()
                    startMonth = parseInt(startMonth, 10)

                   if(doc.status=="5" || doc.status=="6"){
                        endYear = dataEnd.split("-")[0].toString()
                        endYear = parseInt(endYear, 10)
                        endMonth = dataEnd.split("-")[1].toString()
                        endMonth = parseInt(endMonth, 10)
                    } else {
                        date = new Date()
                        endYear = date.toISOString().substring(0,4)
                        endYear = parseInt(endYear, 10)    
                        endMonth = date.toISOString().substring(5,7)
                        endMonth = parseInt(endMonth, 10)
                    }

                    for(i=0;true;i++) {
                        if(startYear > endYear || (startYear == endYear && startMonth > endMonth)) break;
                        m = startMonth+""
                        if(m.length==1)
                            m="0"+m
                        emit(startYear+"-"+m, 1);
                        startMonth += 1;
                        if(startMonth == 13) {
                            startMonth = 1;
                            startYear += 1;
                        }
                    }
              }
            }

           '''
    reduce = '''
                function(keys, values, rereduce) {
                    return sum(values);
                }
             '''
    view=couchdb.design.ViewDefinition('issueMonthCount', 'issueMonthCount', map_fun=map, reduce_fun=reduce)
    view.sync(database)

def issuesYearCounter(database):
    # view that counts the issues in a given year
    map = '''
            function(doc) {
                if (doc.doc_type == "Issue")
                    dataStart=doc.dateReported.substring(0,4)
                    dataEnd=doc.dateUpdated.substring(0,4)
                    startYear = parseInt(dataStart.split("-")[0])
                    if(doc.status=="5" || doc.status=="6"){
                        endYear = parseInt(dataEnd.split("-")[0]).toString()
                        endYear = parseInt(endYear, 10)  
                    } else {
                        date = newDate()
                        endYear = parseInt(date.toISOString().substring(0,4)).toString()
                        endYear = parseInt(endYear, 10)  
                    }
    
                    for(i=0;true;i++) {
                        if(startYear > endYear) break;
                        emit(startYear, 1);
                        startYear += 1;
                    }
            }
           '''
    reduce = '''
                function(keys, values, rereduce) {
                    return sum(values);
                }
             '''
    view=couchdb.design.ViewDefinition('issueYearCount', 'issueYearCount', map_fun=map, reduce_fun=reduce)
    view.sync(database)
    
def issuesDayCounter(database):
    # view that counts the issues in a given day
    map = '''
           function(doc) {
                if(doc.doc_type=="Issue"){
                    dataStart=doc.dateReported.substring(0,10)
                    startYear = dataStart.split("-")[0].toString()
                    startYear = parseInt(startYear, 10)
                    startMonth = dataStart.split("-")[1].toString()
                    startMonth = parseInt(startMonth, 10)
                    startDay = dataStart.split("-")[2].toString()
                    startDay = parseInt(startDay, 10)

                   if(doc.status=="5" || doc.status=="6"){
                        dataEnd=doc.dateUpdated.substring(0,10)
                        endYear = dataEnd.split("-")[0].toString()
                        endYear = parseInt(endYear, 10)
                        endMonth = dataEnd.split("-")[1].toString()
                        endMonth = parseInt(endMonth, 10)
                        endDay = dataEnd.split("-")[2].toString()
                        endDay = parseInt(endDay, 10)
                    } else {
                        date = new Date()
                        endYear = date.toISOString().substring(0,4)
                        endYear = parseInt(endYear, 10)    
                        endMonth = date.toISOString().substring(5,7)
                        endMonth = parseInt(endMonth, 10)
                        endDay = date.toISOString().substring(8,10)
                        endDay = parseInt(endDay, 10)
                    }

                    for(i=0;true;i++) {
                        if(startYear > endYear || (startYear == endYear && startMonth > endMonth) || (startYear == endYear && startMonth == endMonth && startDay > endDay)) break;
                        m = startMonth+""
                        if(m.length==1)
                            m="0"+m
                        d = startDay+""
                        if(d.length==1)
                            d="0"+d
                        emit(startYear+"-"+m+"-"+d, 1);
                        startDay += 1;
                        if(startDay == 29 && startMonth == 2){
                            startDay = 1;
                            startMonth += 1;
                        }else if(startDay == 31 && (startMonth==4 || startMonth==6 || startMonth==9 || startMonth==11)){
                            startDay = 1;
                            startMonth += 1;
                        }else if(startDay == 32){
                            startDay = 1;
                            startMonth += 1;
                        }
                        if(startMonth == 13) {
                            startDay = 1;
                            startMonth = 1;
                            startYear += 1;
                        }
                    }
              }
            }

           '''
    reduce = '''
                function(keys, values, rereduce) {
                    return sum(values);
                }
             '''
    view=couchdb.design.ViewDefinition('issueDayCount', 'issueDayCount', map_fun=map, reduce_fun=reduce)
    view.sync(database)    
    
####################################################################################################################

def addViews(serverName, databaseName):
    # add the view to the given server and database names
    server = couchdb.Server(serverName)
    database = server[databaseName]
    # create all the view for emails
    emailView(database)
    emailsMonthCounter(database)
    emailsYearCounter(database)
    emailsDayCounter(database)
    
    # create all the views for commits
    commitView(database)    
    commitsMonthCounter(database)
    commitsYearCounter(database)
    commitsDayCounter(database)
    
    # create all the views for issues
    issueView(database)
    issuesMonthCounter(database)
    issuesYearCounter(database)
    issuesDayCounter(database)
     